package com.epi.two.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author dxy
 * @version 1.0
 */
@Slf4j
public class ServerDemo {
    public static void main(String[] args) {
        var counter = 1;
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Accepted" + counter++);
                Thread thread = new Thread(new ThreadTaskHandler(socket));
                thread.start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    static class ThreadTaskHandler implements Runnable {
        private Socket socket;

        public ThreadTaskHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (var in = new Scanner(this.socket.getInputStream(), StandardCharsets.UTF_8);
                 var out = new PrintWriter(this.socket.getOutputStream(), true)) {
                out.println("Hello, enter BYE to exit.");
                var done = false;
                while (!done && in.hasNextLine()) {
                    String line = in.nextLine();
                    log.info("[REQUEST] {}", line);
                    out.println(response(line));
                    if (line.equals("BYE")) {
                        done = true;
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }

    private static String response(String request) {
        return switch (request) {
            case "小王" -> "1000";
            case "小李" -> "2000";
            case "小张" -> "3000";
            case "BYE" -> "Bye~";
            default -> "查无此人";
        };
    }
}
